package cn.ly817.jay.interceptor;

import cn.ly817.jay.entity.User;
import cn.ly817.jay.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 * 拦截所有请求
 * 1.验证用户名和密码
 * 2.根据请求中的信息，判断情景
 *   -网页端还是手机端
 *   -被拦截前请求的地址和角色结合
 * Created by LuoYu on 2016/11/21.
 */

public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    /**
     *
     * @param request
     * @param response
     * @param controller:被拦截请求的目标对象-即被拦截controller的实例
     * @return 返回值表示是否将请求拦截下来
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object controller) throws Exception {
        User loginUser = (User)request.getSession().getAttribute("loginUser");
        if(loginUser == null){
            response.sendRedirect(request.getContextPath() + "/u/l/login");
            return false;
        }else{
            return true;
        }

    }

    /**
     *
     * @param request
     * @param response
     * @param controller
     * @param modelAndView:修改视图
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object controller, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 用来关闭资源
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object controller, Exception e) throws Exception {

    }
}
